package com.ximi.ximimall.category.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import javax.validation.constraints.NotNull;
import com.ximi.ximimall.category.service.LitemallCategoryService;
import com.ximi.ximimall.category.service.LitemallGoodsService;
import com.ximi.ximimall.common.component.LocalCache;
import com.ximi.ximimall.common.util.ResponseUtil;
import com.ximi.ximimall.model.LitemallCategory;

import com.ximi.ximimall.model.LitemallGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 西米的风
 * @description TODO
 * @date 2022-10-23 8:45
 */
@RestController
@RequestMapping("/wx/category")
public class CategoryController {

    @Autowired
    private LitemallCategoryService categoryService;

    @Autowired
    private LitemallGoodsService goodsService;

    @Autowired
    private LocalCache localCache;

    private static String QUERY_CHANNEL_KEY = "query_channel_key";

    private static String QUERY_FLOORGOODSLIST_KEY = "QUERY_FLOORGOODSLIST_KEY";

    private static String CATEGORY_INDEX_KEY = "category_index_key";

    private static String CATEGORY_CURRENT_KEY = "category_current_key_";

    private static String CATEGORY_GOODS_ID_KEY = "category_goods_id_key";

    @RequestMapping("/queryChannel")
    public Object queryChannel() {
        List<LitemallCategory> list  = (List<LitemallCategory>) localCache.get(QUERY_CHANNEL_KEY);
        if(CollectionUtil.isNotEmpty(list)){
            return ResponseUtil.ok(list);
        }
        list  = categoryService.queryChannel();
        localCache.setLocalCache(QUERY_CHANNEL_KEY,list);
        return ResponseUtil.ok(list);
    }

    @RequestMapping("/queryFloorGoodsList")
    public Object floorGoodsList() {
        List<Map> list  = (List<Map>) localCache.get(QUERY_FLOORGOODSLIST_KEY);
        if(CollectionUtil.isNotEmpty(list)){
            return ResponseUtil.ok(list);
        }
        list  = getCategoryList();
        localCache.setLocalCache(QUERY_FLOORGOODSLIST_KEY,list);
        return ResponseUtil.ok(list);
    }

    private List<Map> getCategoryList() {
        List<Map> categoryList = new ArrayList<>();
        List<LitemallCategory> catL1List = categoryService.queryL1WithoutRecommend(0, 4);
        for (LitemallCategory catL1 : catL1List) {
            List<LitemallCategory> catL2List = categoryService.queryByPid(catL1.getId());
            List<Integer> l2List = new ArrayList<>();
            for (LitemallCategory catL2 : catL2List) {
                l2List.add(catL2.getId());
            }

            List<LitemallGoods> categoryGoods;
            if (l2List.size() == 0) {
                categoryGoods = new ArrayList<>();
            } else {
                categoryGoods = goodsService.queryByCategory(l2List, 0, 4);
            }

            Map<String, Object> catGoods = new HashMap<>();
            catGoods.put("id", catL1.getId());
            catGoods.put("name", catL1.getName());
            catGoods.put("goodsList", categoryGoods);
            categoryList.add(catGoods);
        }
        return categoryList;
    }


    @RequestMapping("/index")
    public Object index() {
        Map<String, Object> data  = (Map<String, Object>) localCache.get(CATEGORY_INDEX_KEY);
        if(CollectionUtil.isNotEmpty(data)){
            return ResponseUtil.ok(data);
        }
        // 所有一级分类目录
        List<LitemallCategory> l1CatList = categoryService.queryL1();

        // 当前一级分类目录
        LitemallCategory currentCategory = null;
        if (l1CatList.size() > 0) {
            currentCategory = l1CatList.get(0);
        }

        // 当前一级分类目录对应的二级分类目录
        List<LitemallCategory> currentSubCategory = null;
        if (null != currentCategory) {
            currentSubCategory = categoryService.queryByPid(currentCategory.getId());
        }

        data = new HashMap<String, Object>();
        data.put("categoryList", l1CatList);
        data.put("currentCategory", currentCategory);
        data.put("currentSubCategory", currentSubCategory);

        localCache.setLocalCache(CATEGORY_INDEX_KEY, data);
        return ResponseUtil.ok(data);

    }


    /**
     * 当前分类栏目
     *
     * @param id 分类类目ID
     * @return 当前分类栏目
     */
    @RequestMapping("/current")
    public Object current(@NotNull Integer id) {
        String cacheKey = CATEGORY_CURRENT_KEY+id;
        Map<String, Object> data  = (Map<String, Object>) localCache.get(cacheKey);
        if(CollectionUtil.isNotEmpty(data)){
            return ResponseUtil.ok(data);
        }
        // 当前分类
        LitemallCategory currentCategory = categoryService.findById(id);
        if(currentCategory == null){
            return ResponseUtil.badArgumentValue();
        }
        List<LitemallCategory> currentSubCategory = categoryService.queryByPid(currentCategory.getId());

        data = new HashMap<String, Object>();
        data.put("currentCategory", currentCategory);
        data.put("currentSubCategory", currentSubCategory);

        localCache.setLocalCache(cacheKey, data);
        return ResponseUtil.ok(data);
    }

    /**
     * 商品分类类目
     *
     * @param id 分类类目ID
     * @return 商品分类类目
     */
    @RequestMapping("/goodsId")
    public Object category(@NotNull Integer id) {
        String cacheKey = CATEGORY_GOODS_ID_KEY +id;
        Map<String, Object> data  = (Map<String, Object>) localCache.get(cacheKey);
        if(CollectionUtil.isNotEmpty(data)){
            return ResponseUtil.ok(data);
        }
        LitemallCategory cur = categoryService.findById(id);
        LitemallCategory parent = null;
        List<LitemallCategory> children = null;

        if (cur.getPid() == 0) {
            parent = cur;
            children = categoryService.queryByPid(cur.getId());
            cur = children.size() > 0 ? children.get(0) : cur;
        } else {
            parent = categoryService.findById(cur.getPid());
            children = categoryService.queryByPid(cur.getPid());
        }
        data = new HashMap<>();
        data.put("currentCategory", cur);
        data.put("parentCategory", parent);
        data.put("brotherCategory", children);

        localCache.setLocalCache(cacheKey, data);
        return ResponseUtil.ok(data);
    }


    /**
     * 根据条件搜素商品
     * <p>
     * 1. 这里的前五个参数都是可选的，甚至都是空
     * 2. 用户是可选登录，如果登录，则记录用户的搜索关键字
     *
     * @param categoryId 分类类目ID，可选
     * @param brandId    品牌商ID，可选
     * @param keyword    关键字，可选
     * @param isNew      是否新品，可选
     * @param isHot      是否热买，可选
     * @param userId     用户ID
     * @param page       分页页数
     * @param limit       分页大小
     * @param sort       排序方式，支持"add_time", "retail_price"或"name"
     * @param order      排序类型，顺序或者降序
     * @return 根据条件搜素的商品详情
     */
    @RequestMapping("/goods/list")
    public Object list(
            Integer categoryId,
            Integer brandId,
            String keyword,
            Boolean isNew,
            Boolean isHot,
            Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "add_time") String sort,
            @RequestParam(defaultValue = "desc") String order) {

        //添加到搜索历史
//        if (userId != null && !StringUtils.isEmpty(keyword)) {
//            LitemallSearchHistory searchHistoryVo = new LitemallSearchHistory();
//            searchHistoryVo.setKeyword(keyword);
//            searchHistoryVo.setUserId(userId);
//            searchHistoryVo.setFrom("wx");
//            searchHistoryService.save(searchHistoryVo);
//        }

        //查询列表数据
        List<LitemallGoods> goodsList = goodsService.querySelective(categoryId, brandId, keyword, isHot, isNew, page, limit, sort, order);

        // 查询商品所属类目列表。
        List<Integer> goodsCatIds = goodsService.getCatIds(brandId, keyword, isHot, isNew);
        List<LitemallCategory> categoryList = null;
        if (goodsCatIds.size() != 0) {
            categoryList = categoryService.queryL2ByIds(goodsCatIds);
        } else {
            categoryList = new ArrayList<>(0);
        }

        PageInfo<LitemallGoods> pagedList = PageInfo.of(goodsList);

        Map<String, Object> entity = new HashMap<>();
        entity.put("list", goodsList);
        entity.put("total", pagedList.getTotal());
        entity.put("page", pagedList.getPageNum());
        entity.put("limit", pagedList.getPageSize());
        entity.put("pages", pagedList.getPages());
        entity.put("filterCategoryList", categoryList);

        // 因为这里需要返回额外的filterCategoryList参数，因此不能方便使用ResponseUtil.okList
        return ResponseUtil.ok(entity);
    }

}
